package com.cloud.pole.shop.controller.order;

import java.net.URLDecoder;
import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.cloud.pole.common.constant.CommonConstants;
import com.cloud.pole.common.exception.BaseException;
import com.cloud.pole.common.exception.ParamException;
import com.cloud.pole.common.msg.ApiRestResponse;
import com.cloud.pole.common.util.RegexUtils;
import com.cloud.pole.shop.controller.IndexController;
import com.cloud.pole.shop.model.entity.order.ShopOrder;
import com.cloud.pole.shop.model.vo.IndexVo;
import com.cloud.pole.shop.model.vo.goods.GoodsDetailVo;
import com.cloud.pole.shop.model.vo.goods.ShopGoodsPromotionByTypeVo;
import com.cloud.pole.shop.model.vo.order.ShopOrderPageVo;
import com.cloud.pole.shop.model.vo.order.ShopOrderToConfirmVo;
import com.cloud.pole.shop.model.vo.order.ShopRecommendOrderPageVo;
import com.cloud.pole.shop.model.vo.order.ShopUserOrderDetailVo;
import com.cloud.pole.shop.model.vo.order.ShopUserOrderVo;
import com.cloud.pole.shop.model.vo.order.ShopUserOrderPageVo;
import com.cloud.pole.shop.model.vo.order.ShoppingCartVo;
import com.cloud.pole.shop.service.IndexService;
import com.cloud.pole.shop.service.goods.GoodsService;
import com.cloud.pole.shop.service.order.OrderService;
import com.cloud.pole.shop.service.order.ShoppingCartService;
import com.github.pagehelper.PageInfo;

import lombok.extern.slf4j.Slf4j;

/*
*2019年2月21日
*cloud-shop
*author:frank-chen
*/
@Controller
@Slf4j
@RequestMapping("/order/front")
public class OrderController {

	@Autowired
	private OrderService orderService;
	
	/**
	 * 
	 * @param token
	 * @param cartIds 多个cartId使用“,”隔开
	 * @param cartParams 店铺id-goodsId-goodsSpecId-数量,多个使用“,”隔开
	 * @return
	 */
	@ResponseBody
	@RequestMapping("/addOrder")
    public ApiRestResponse<String> addOrder(
    		@RequestHeader(defaultValue = "") String token,
    		@RequestParam(defaultValue = "") String cartIds,
    		@RequestParam(defaultValue = "") String cartParams,
    		@RequestParam(defaultValue = "") String marketCode){   	
    	try {
    		ParamException.err(StringUtils.isBlank(token), "token不能为空");    		
			ParamException.err(StringUtils.isBlank(cartIds), "cartIds不能为空");    		
			ParamException.err(StringUtils.isBlank(cartParams), "cartParams不能为空");    		

			return ApiRestResponse.success(CommonConstants.STATUS_OK_MESSAGE, orderService.addOrder(token, cartIds, cartParams, marketCode));
    	} catch (BaseException e) {
			return ApiRestResponse.fail(e.getStatus(), e.getMessage(), null);
		} catch (Exception e) {
			log.error(CommonConstants.STATUS_ERROR_MESSAGE + "{}", e.getMessage(), e);
			return ApiRestResponse.fail(CommonConstants.STATUS_ERROR_MESSAGE, null);
		}
    }
	
	/**
	 * 获取添加订单列表
	 * @param token
	 * @param orderIds
	 * @return
	 */
	@ResponseBody
	@RequestMapping("/getToConfirmOrderList")
    public ApiRestResponse<ShopOrderToConfirmVo> getToConfirmOrderList(
    		@RequestHeader(defaultValue = "") String token,
    		@RequestParam(defaultValue = "") String orderIds){   	
    	try {
			ParamException.err(StringUtils.isBlank(token), "token不能为空");    		
			ParamException.err(StringUtils.isBlank(orderIds), "orderIds不能为空");    		

    		orderIds = URLDecoder.decode(orderIds, "UTF-8");
			return ApiRestResponse.success(CommonConstants.STATUS_OK_MESSAGE, orderService.getToConfirmOrderList(token, orderIds));
    	} catch (BaseException e) {
			return ApiRestResponse.fail(e.getStatus(), e.getMessage(), null);
		} catch (Exception e) {
			log.error(CommonConstants.STATUS_ERROR_MESSAGE + "{}", e.getMessage(), e);
			return ApiRestResponse.fail(CommonConstants.STATUS_ERROR_MESSAGE, null);
		}
    }
	
	/**
	 * 确认订单（保存收货地址，用户留言）
	 * @param token
	 * @param orderIds
	 * @param userRemak
	 * @param addrId
	 * @param logisticsType 配送方式（1: 第三方物流, 2: 上门自提 3：送货上门）
	 * @param payMethod 付款方式（1：在线支付  2：到店支付 3：货到付款 ）
	 * @return
	 */
	@ResponseBody
	@RequestMapping("/confirmOrders")
    public ApiRestResponse<Long> confirmOrders(
    		@RequestHeader(defaultValue = "") String token,
    		@RequestParam(defaultValue = "") String orderIds,
    		@RequestParam(defaultValue = "") String userRemak,
    		@RequestParam(defaultValue = "") String addrId,
    		@RequestParam(defaultValue = "1") String logisticsType,
    		@RequestParam(defaultValue = "1") String payMethod,
    		@RequestParam(defaultValue = "") String recommandMarketCode){   	
    	try {
			ParamException.err(StringUtils.isBlank(token), "token不能为空");    		
			ParamException.err(StringUtils.isBlank(orderIds), "orderIds不能为空");

			ParamException.err(StringUtils.isBlank(logisticsType), "logisticsType不能为空");
			ParamException.err(!RegexUtils.isPositiveInteger(logisticsType), "logisticsType错误");
			ParamException.err(StringUtils.isBlank(payMethod), "payMethod不能为空");
			ParamException.err(!RegexUtils.isPositiveInteger(payMethod), "payMethod错误");
			Integer nAddrId = null;
			//需要把logisticsType，payMethod对应关系限制死
			//不是在线支付需要限制快递方式
			if(Integer.parseInt(payMethod) != ShopOrder.PAY_METHOD_ONLINE) {
				if(Integer.parseInt(logisticsType) == ShopOrder.LOGISTICS_TYPE_HOME_DELIVERY && 
					Integer.parseInt(payMethod) != ShopOrder.PAY_METHOD_CASH_ON_DELIVERY){
					throw new BaseException(CommonConstants.STATUS_ERROR_CODE, "支付方式、派送方式错误");
				}
				if(Integer.parseInt(logisticsType) == ShopOrder.LOGISTICS_TYPE_SELF_MENTION && 
					Integer.parseInt(payMethod) != ShopOrder.PAY_METHOD_TO_SHOP){
					throw new BaseException(CommonConstants.STATUS_ERROR_CODE, "支付方式、派送方式错误");
				}				
			}
			//如果第三方配送和送货上门addrId不能为空
			if(Integer.parseInt(logisticsType) == ShopOrder.LOGISTICS_TYPE_EXPRESS || 
			    Integer.parseInt(logisticsType) == ShopOrder.LOGISTICS_TYPE_HOME_DELIVERY) {
				ParamException.err(StringUtils.isBlank(addrId), "addrId不能为空");
				ParamException.err(!RegexUtils.isPositiveInteger(addrId), "addrId错误");
				nAddrId = Integer.parseInt(addrId);
			}
    		orderIds = URLDecoder.decode(orderIds, "UTF-8");
			return ApiRestResponse.success(CommonConstants.STATUS_OK_MESSAGE, orderService.confirmOrders(token, orderIds, userRemak, 
					nAddrId, Integer.parseInt(logisticsType), Integer.parseInt(payMethod), recommandMarketCode));
    	} catch (BaseException e) {
			return ApiRestResponse.fail(e.getStatus(), e.getMessage(), null);
		} catch (Exception e) {
			log.error(CommonConstants.STATUS_ERROR_MESSAGE + "{}", e.getMessage(), e);
			return ApiRestResponse.fail(CommonConstants.STATUS_ERROR_MESSAGE, null);
		}
    }
	

	/**
	 * 立即购买（加入订单、保存收货地址、用户留言）
	 * @param token
	 * @param orderIds
	 * @param userRemak
	 * @param addrId
	 * @return
	 */
	@ResponseBody
	@RequestMapping("/immediatePurchase")
    public ApiRestResponse<String> immediatePurchase(
    		@RequestHeader(defaultValue = "") String token,
    		@RequestParam(defaultValue = "") String productNum,
    		@RequestParam(defaultValue = "") String specId){   	
    	try {
			ParamException.err(StringUtils.isBlank(token), "token不能为空");    		
			ParamException.err(StringUtils.isBlank(productNum), "productNum不能为空");
			ParamException.err(StringUtils.isBlank(specId), "specId不能为空");
			ParamException.err(!RegexUtils.isPositiveInteger(productNum), "productNum错误");
			ParamException.err(!RegexUtils.isPositiveInteger(specId), "specId错误");
			return ApiRestResponse.success(CommonConstants.STATUS_OK_MESSAGE, orderService.immediatePurchase(token, Integer.parseInt(specId), Integer.parseInt(productNum)));
    	} catch (BaseException e) {
			return ApiRestResponse.fail(e.getStatus(), e.getMessage(), null);
		} catch (Exception e) {
			log.error(CommonConstants.STATUS_ERROR_MESSAGE + "{}", e.getMessage(), e);
			return ApiRestResponse.fail(CommonConstants.STATUS_ERROR_MESSAGE, null);
		}
    }

	@ResponseBody
	@RequestMapping("/getUserOrderList")
    public ApiRestResponse<ShopUserOrderPageVo> getUserOrderList(
    		@RequestHeader(name="token", defaultValue = "") String token,
    		@RequestParam(name="searchType", defaultValue="") String searchType,
    		@RequestParam(name="pageSize", defaultValue="") String pageSize,
    		@RequestParam(name="pageNum", defaultValue="") String pageNum){   	
    	try {
			ParamException.err(StringUtils.isBlank(token), "token不能为空");    		
			ParamException.err(StringUtils.isBlank(searchType), "searchType不能为空");    		
			ParamException.err(StringUtils.isBlank(pageSize), "pageSize不能为空");
			ParamException.err(!RegexUtils.isInteger(searchType), "searchType错误");
			ParamException.err(!RegexUtils.isPositiveInteger(pageSize), "pageSize错误");
			ParamException.err(StringUtils.isBlank(pageNum), "pageNum错误");
			ParamException.err(!RegexUtils.isPositiveInteger(pageNum), "pageNum错误");
			return ApiRestResponse.success(CommonConstants.STATUS_OK_MESSAGE, orderService.getPageUserOrderList(token, Integer.parseInt(searchType), Integer.parseInt(pageSize), Integer.parseInt(pageNum)));
    	} catch (BaseException e) {
			return ApiRestResponse.fail(e.getStatus(), e.getMessage(), null);
		} catch (Exception e) {
			log.error(CommonConstants.STATUS_ERROR_MESSAGE + "{}", e.getMessage(), e);
			return ApiRestResponse.fail(CommonConstants.STATUS_ERROR_MESSAGE, null);
		}
    }
	
	@ResponseBody
	@RequestMapping("/getUserOrderDetail")
    public ApiRestResponse<ShopUserOrderDetailVo> getUserOrderDetail(
    		@RequestHeader(name="token", defaultValue = "") String token,
    		@RequestParam(name="orderId", defaultValue="") String orderId){   	
    	try {
			ParamException.err(StringUtils.isBlank(token), "token不能为空");    		
			ParamException.err(StringUtils.isBlank(orderId), "orderId不能为空");    		
			return ApiRestResponse.success(CommonConstants.STATUS_OK_MESSAGE, orderService.getUserOrderDetail(token, orderId));
    	} catch (BaseException e) {
			return ApiRestResponse.fail(e.getStatus(), e.getMessage(), null);
		} catch (Exception e) {
			log.error(CommonConstants.STATUS_ERROR_MESSAGE + "{}", e.getMessage(), e);
			return ApiRestResponse.fail(CommonConstants.STATUS_ERROR_MESSAGE, null);
		}
    }
	
	/**
	 * 确认收货
	 * @param token
	 * @param cartIds
	 * @param cartParams
	 * @return
	 */
	@ResponseBody
	@RequestMapping("/confirmReceiveGoods")
    public ApiRestResponse<Boolean> confirmReceiveGoods(
    		@RequestHeader(defaultValue = "") String token,
    		@RequestParam(defaultValue = "") String orderId){   	
    	try {
			return ApiRestResponse.success(CommonConstants.STATUS_OK_MESSAGE, orderService.confirmReceiveGoods(token, orderId));
    	} catch (BaseException e) {
			return ApiRestResponse.fail(e.getStatus(), e.getMessage(), null);
		} catch (Exception e) {
			log.error(CommonConstants.STATUS_ERROR_MESSAGE + "{}", e.getMessage(), e);
			return ApiRestResponse.fail(CommonConstants.STATUS_ERROR_MESSAGE, null);
		}
    }
	
	/**
	 * 取消未支付订单
	 * @param token
	 * @param orderId
	 * @return
	 */
	@ResponseBody
	@RequestMapping("/cancelOrder")
    public ApiRestResponse<Boolean> cancelOrder(
    		@RequestHeader(defaultValue = "") String token,
    		@RequestParam(defaultValue = "") String orderId){   	
    	try {
			return ApiRestResponse.success(CommonConstants.STATUS_OK_MESSAGE, orderService.cancelOrder(token, orderId));
    	} catch (BaseException e) {
			return ApiRestResponse.fail(e.getStatus(), e.getMessage(), null);
		} catch (Exception e) {
			log.error(CommonConstants.STATUS_ERROR_MESSAGE + "{}", e.getMessage(), e);
			return ApiRestResponse.fail(CommonConstants.STATUS_ERROR_MESSAGE, null);
		}
    }
	
	/**
	 * 删除订单显示
	 * @param token
	 * @param orderId
	 * @return
	 */
	@ResponseBody
	@RequestMapping("/delOrder")
    public ApiRestResponse<Boolean> delOrder(
    		@RequestHeader(defaultValue = "") String token,
    		@RequestParam(defaultValue = "") String orderId){   	
    	try {
			return ApiRestResponse.success(CommonConstants.STATUS_OK_MESSAGE, orderService.delOrder(token, orderId));
    	} catch (BaseException e) {
			return ApiRestResponse.fail(e.getStatus(), e.getMessage(), null);
		} catch (Exception e) {
			log.error(CommonConstants.STATUS_ERROR_MESSAGE + "{}", e.getMessage(), e);
			return ApiRestResponse.fail(CommonConstants.STATUS_ERROR_MESSAGE, null);
		}
    }
	
	@ResponseBody
	@RequestMapping("/getShopOrderList")
    public ApiRestResponse<ShopOrderPageVo> getShopOrderList(
    		@RequestHeader(name="token", defaultValue = "") String token,
    		@RequestParam(name="shopId", defaultValue = "") String shopId,
    		@RequestParam(name="searchType", defaultValue="0") String searchType,
    		@RequestParam(name="pageSize", defaultValue="") String pageSize,
    		@RequestParam(name="pageNum", defaultValue="") String pageNum){   	
    	try {
			ParamException.err(StringUtils.isBlank(token), "token不能为空");    		
			ParamException.err(StringUtils.isBlank(shopId), "shopId不能为空");
			ParamException.err(!RegexUtils.isPositiveInteger(shopId), "shopId错误");
		
			ParamException.err(StringUtils.isBlank(searchType), "searchType不能为空");    		
			ParamException.err(StringUtils.isBlank(pageSize), "pageSize不能为空");
			ParamException.err(!RegexUtils.isInteger(searchType), "searchType错误");
			ParamException.err(!RegexUtils.isPositiveInteger(pageSize), "pageSize错误");
			ParamException.err(StringUtils.isBlank(pageNum), "pageNum不能为空");
			ParamException.err(!RegexUtils.isPositiveInteger(pageNum), "pageNum错误");
		
			return ApiRestResponse.success(CommonConstants.STATUS_OK_MESSAGE, orderService.getPageShopOrderList(token, Integer.parseInt(shopId), Integer.parseInt(searchType), Integer.parseInt(pageSize), Integer.parseInt(pageNum)));
    	} catch (BaseException e) {
			return ApiRestResponse.fail(e.getStatus(), e.getMessage(), null);
		} catch (Exception e) {
			log.error(CommonConstants.STATUS_ERROR_MESSAGE + "{}", e.getMessage(), e);
			return ApiRestResponse.fail(CommonConstants.STATUS_ERROR_MESSAGE, null);
		}
    }
	
	/**
	 * 店铺确认发货(线下)
	 * @param token
	 * @param orderId
	 * @return
	 */
	@ResponseBody
	@RequestMapping("/confirmDeliverOffLine")
    public ApiRestResponse<Boolean> confirmDeliverOffLine(
    		@RequestHeader(name="token", defaultValue = "") String token,
    		@RequestParam(name="orderId", defaultValue = "") String orderId){   	
    	try {
			ParamException.err(StringUtils.isBlank(token), "token不能为空");    		
			ParamException.err(StringUtils.isBlank(orderId), "orderId不能为空");
		
			return ApiRestResponse.success(CommonConstants.STATUS_OK_MESSAGE, orderService.confirmDeliverOffLine(token, orderId));
    	} catch (BaseException e) {
			return ApiRestResponse.fail(e.getStatus(), e.getMessage(), null);
		} catch (Exception e) {
			log.error(CommonConstants.STATUS_ERROR_MESSAGE + "{}", e.getMessage(), e);
			return ApiRestResponse.fail(CommonConstants.STATUS_ERROR_MESSAGE, null);
		}
    }
	
	@ResponseBody
	@RequestMapping("/getRecommendOrderList")
    public ApiRestResponse<ShopRecommendOrderPageVo> getRecommendOrderList(
    		@RequestHeader(name="token", defaultValue = "") String token,
    		@RequestParam(name="searchType", defaultValue="") String searchType,
    		@RequestParam(name="pageSize", defaultValue="") String pageSize,
    		@RequestParam(name="pageNum", defaultValue="") String pageNum){   	
    	try {
			ParamException.err(StringUtils.isBlank(token), "token不能为空");    		
			ParamException.err(StringUtils.isBlank(searchType), "searchType不能为空");    		
			ParamException.err(StringUtils.isBlank(pageSize), "pageSize不能为空");
			ParamException.err(!RegexUtils.isInteger(searchType), "searchType错误");
			ParamException.err(!RegexUtils.isPositiveInteger(pageSize), "pageSize错误");
			ParamException.err(StringUtils.isBlank(pageNum), "pageNum错误");
			ParamException.err(!RegexUtils.isPositiveInteger(pageNum), "pageNum错误");
			return ApiRestResponse.success(CommonConstants.STATUS_OK_MESSAGE, orderService.getRecommendOrderList(token, Integer.parseInt(searchType), Integer.parseInt(pageSize), Integer.parseInt(pageNum)));
    	} catch (BaseException e) {
			return ApiRestResponse.fail(e.getStatus(), e.getMessage(), null);
		} catch (Exception e) {
			log.error(CommonConstants.STATUS_ERROR_MESSAGE + "{}", e.getMessage(), e);
			return ApiRestResponse.fail(CommonConstants.STATUS_ERROR_MESSAGE, null);
		}
    }
}
